import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ViewStyle, StyleProp, Image, View, ActivityIndicator, Text } from 'react-native';
import { NativeModules } from 'react-native';

interface SecureImageViewProps {
  source: { uri: string };
  style?: StyleProp<ViewStyle>;
  onLoadStart?: () => void;
  onLoadEnd?: () => void;
  serverInfo?: any;
}

// 简单的内存缓存
const imageCache = new Map<string, { data: string; timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

const SecureImageView: React.FC<SecureImageViewProps> = React.memo((props) => {
  const [imageData, setImageData] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const mountedRef = useRef(true);

  // 清理缓存
  const cleanupCache = useCallback(() => {
    const now = Date.now();
    for (const [key, value] of imageCache.entries()) {
      if (now - value.timestamp > CACHE_DURATION) {
        imageCache.delete(key);
      }
    }
  }, []);

  // 从缓存获取图片
  const getCachedImage = useCallback((uri: string): string | null => {
    const cached = imageCache.get(uri);
    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
      return cached.data;
    }
    return null;
  }, []);

  // 缓存图片数据
  const cacheImage = useCallback((uri: string, data: string) => {
    imageCache.set(uri, { data, timestamp: Date.now() });
  }, []);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    const loadImage = async () => {
      const { uri } = props.source;
      console.log('🖼️ SecureImageView 开始加载图片:', uri);
      
      // 检查缓存
      const cachedData = getCachedImage(uri);
      if (cachedData) {
        console.log('🖼️ 使用缓存图片数据');
        if (mountedRef.current) {
          setImageData(cachedData);
          setError(false);
        }
        return;
      }
      
      // 如果是相对路径，尝试通过 Native Module 获取图片数据
      if (uri.startsWith('cards/') || uri.includes('card_') || uri.startsWith('images/')) {
        try {
          if (mountedRef.current) {
            setLoading(true);
            setError(false);
            props.onLoadStart?.();
          }
          console.log('🔄 通过 Native Module 获取图片...');
          
          // 调用 Native Module
          const result = await NativeModules.ApiModule.getImageData(uri, props.serverInfo);
          console.log('✅ 图片数据获取成功:', result);
          
          if (result && result.data && mountedRef.current) {
            console.log('🖼️ 设置图片数据，大小:', result.size);
            setImageData(result.data);
            setError(false);
            // 缓存图片数据
            cacheImage(uri, result.data);
          } else {
            console.warn('⚠️ 图片数据为空');
            if (mountedRef.current) {
              setError(true);
            }
          }
        } catch (error) {
          console.error('❌ 获取图片数据失败:', error);
          if (mountedRef.current) {
            setError(true);
          }
        } finally {
          if (mountedRef.current) {
            setLoading(false);
            props.onLoadEnd?.();
          }
        }
      } else {
        // 不是相对路径，直接使用原始 URI
        console.log('🖼️ 使用原始 URI');
        if (mountedRef.current) {
          setImageData(uri);
          setError(false);
        }
      }
    };

    loadImage();
    
    // 定期清理缓存
    const cleanupInterval = setInterval(cleanupCache, CACHE_DURATION);
    return () => {
      clearInterval(cleanupInterval);
    };
  }, [props.source.uri, getCachedImage, cacheImage, cleanupCache, props.onLoadStart, props.onLoadEnd]);

  console.log('🖼️ SecureImageView 渲染，imageData:', imageData ? '有数据' : '无数据', 'loading:', loading, 'error:', error);

  // 如果有图片数据，使用 Image 组件显示
  if (imageData) {
    console.log('🖼️ 使用 Image 组件显示图片');
    return (
      <View style={props.style}>
        <Image
          source={{ uri: imageData }}
          style={{ width: '100%', height: '100%' }}
          resizeMode="cover"
          onLoadStart={() => {
            console.log('✅ 图片加载开始');
            props.onLoadStart?.();
          }}
          onLoad={() => {
            console.log('✅ 图片加载成功');
            props.onLoadEnd?.();
          }}
          onError={(error) => {
            console.error('❌ 图片加载失败:', error);
            props.onLoadEnd?.();
            if (mountedRef.current) {
              setError(true);
            }
          }}
        />
        {error && (
          <View style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: '#2a2a2a',
            justifyContent: 'center',
            alignItems: 'center',
          }}>
            <Text style={{ color: '#888', fontSize: 12 }}>图片加载失败</Text>
          </View>
        )}
      </View>
    );
  }

  // 加载状态
  if (loading) {
    return (
      <View style={[props.style, { justifyContent: 'center', alignItems: 'center', backgroundColor: '#2a2a2a' }]}>
        <ActivityIndicator size="small" color="#4a90e2" />
      </View>
    );
  }

  // 错误状态
  if (error) {
    return (
      <View style={[props.style, { justifyContent: 'center', alignItems: 'center', backgroundColor: '#2a2a2a' }]}>
        <Text style={{ color: '#888', fontSize: 12 }}>图片加载失败</Text>
      </View>
    );
  }

  // 默认状态
  return (
    <View style={[props.style, { justifyContent: 'center', alignItems: 'center', backgroundColor: '#2a2a2a' }]}>
      <Text style={{ color: '#888', fontSize: 12 }}>加载中...</Text>
    </View>
  );
});

SecureImageView.displayName = 'SecureImageView';

export default SecureImageView; 